package com.yonglian.management.web.rest;

import com.yonglian.management.domain.Activity;
import com.yonglian.management.domain.ActivityProperty;
import com.yonglian.management.repository.ActivityPropertyRepository;
import com.yonglian.management.service.ActivityPropertyService;
import com.yonglian.management.web.rest.errors.BadRequestAlertException;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.PaginationUtil;
import tech.jhipster.web.util.ResponseUtil;

/**
 * REST controller for managing {@link com.yonglian.management.domain.ActivityProperty}.
 */
@RestController
@RequestMapping("/api/activity-properties")
public class ActivityPropertyResource {

    private final Logger log = LoggerFactory.getLogger(ActivityPropertyResource.class);

    private static final String ENTITY_NAME = "activityProperty";

    @Value("${jhipster.clientApp.name}")
    private String applicationName;

    private final ActivityPropertyService activityPropertyService;

    private final ActivityPropertyRepository activityPropertyRepository;

    public ActivityPropertyResource(
        ActivityPropertyService activityPropertyService,
        ActivityPropertyRepository activityPropertyRepository
    ) {
        this.activityPropertyService = activityPropertyService;
        this.activityPropertyRepository = activityPropertyRepository;
    }

    /**
     * {@code POST  /activity-properties} : Create a new activityProperty.
     *
     * @param activityProperty the activityProperty to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new activityProperty, or with status {@code 400 (Bad Request)} if the activityProperty has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("")
    public ResponseEntity<ActivityProperty> createActivityProperty(@Valid @RequestBody ActivityProperty activityProperty)
        throws URISyntaxException {
        log.debug("REST request to save ActivityProperty : {}", activityProperty);
        if (activityProperty.getId() != null) {
            throw new BadRequestAlertException("A new activityProperty cannot already have an ID", ENTITY_NAME, "idexists");
        }
        activityProperty = activityPropertyService.save(activityProperty);
        return ResponseEntity.created(new URI("/api/activity-properties/" + activityProperty.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, activityProperty.getId().toString()))
            .body(activityProperty);
    }

    /**
     * {@code PUT  /activity-properties/:id} : Updates an existing activityProperty.
     *
     * @param id the id of the activityProperty to save.
     * @param activityProperty the activityProperty to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated activityProperty,
     * or with status {@code 400 (Bad Request)} if the activityProperty is not valid,
     * or with status {@code 500 (Internal Server Error)} if the activityProperty couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/{id}")
    public ResponseEntity<ActivityProperty> updateActivityProperty(
        @PathVariable(value = "id", required = false) final Long id,
        @Valid @RequestBody ActivityProperty activityProperty
    ) throws URISyntaxException {
        log.debug("REST request to update ActivityProperty : {}, {}", id, activityProperty);
        if (activityProperty.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, activityProperty.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!activityPropertyRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        activityProperty = activityPropertyService.update(activityProperty);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, activityProperty.getId().toString()))
            .body(activityProperty);
    }

    /**
     * {@code PATCH  /activity-properties/:id} : Partial updates given fields of an existing activityProperty, field will ignore if it is null
     *
     * @param id the id of the activityProperty to save.
     * @param activityProperty the activityProperty to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated activityProperty,
     * or with status {@code 400 (Bad Request)} if the activityProperty is not valid,
     * or with status {@code 404 (Not Found)} if the activityProperty is not found,
     * or with status {@code 500 (Internal Server Error)} if the activityProperty couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PatchMapping(value = "/{id}", consumes = { "application/json", "application/merge-patch+json" })
    public ResponseEntity<ActivityProperty> partialUpdateActivityProperty(
        @PathVariable(value = "id", required = false) final Long id,
        @NotNull @RequestBody ActivityProperty activityProperty
    ) throws URISyntaxException {
        log.debug("REST request to partial update ActivityProperty partially : {}, {}", id, activityProperty);
        if (activityProperty.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, activityProperty.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!activityPropertyRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        Optional<ActivityProperty> result = activityPropertyService.partialUpdate(activityProperty);

        return ResponseUtil.wrapOrNotFound(
            result,
            HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, activityProperty.getId().toString())
        );
    }

    /**
     * {@code GET  /activity-properties} : get all the activityProperties.
     *
     * @param pageable the pagination information.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of activityProperties in body.
     */
    @GetMapping("")
    public ResponseEntity<List<ActivityProperty>> getAllActivityProperties(
        @org.springdoc.core.annotations.ParameterObject Pageable pageable
    ) {
        log.debug("REST request to get a page of ActivityProperties");
        Page<ActivityProperty> page = activityPropertyService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    @GetMapping("/activity/{id}")
    public ResponseEntity<List<ActivityProperty>> getAllActivityPropertiesByActivityId(@PathVariable("id") Long id) {
        List<ActivityProperty> list = activityPropertyRepository.findByActivityId(id);
        HttpHeaders headers = new HttpHeaders();
        headers.set("X-Total-Count", String.valueOf(list.size()));
        return ResponseEntity.ok().headers(headers).body(list);
    }

    /**
     * {@code GET  /activity-properties/:id} : get the "id" activityProperty.
     *
     * @param id the id of the activityProperty to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the activityProperty, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/{id}")
    public ResponseEntity<ActivityProperty> getActivityProperty(@PathVariable("id") Long id) {
        log.debug("REST request to get ActivityProperty : {}", id);
        Optional<ActivityProperty> activityProperty = activityPropertyService.findOne(id);
        return ResponseUtil.wrapOrNotFound(activityProperty);
    }

    /**
     * {@code DELETE  /activity-properties/:id} : delete the "id" activityProperty.
     *
     * @param id the id of the activityProperty to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteActivityProperty(@PathVariable("id") Long id) {
        log.debug("REST request to delete ActivityProperty : {}", id);
        activityPropertyService.delete(id);
        return ResponseEntity.noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
            .build();
    }
}
